package com.ruoyi.web.controller.caseinfo;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.ruoyi.biz.bean.bo.CaseInfoBO;
import com.ruoyi.biz.bean.bo.CaseInfoClosedBO;
import com.ruoyi.biz.bean.vo.dto.CaseInfoClosedDTO;
import com.ruoyi.biz.bean.vo.dto.CaseUploadFileDTO;
import com.ruoyi.biz.bean.vo.qo.CaseInfoQO;
import com.ruoyi.biz.domain.CaseInfo;
import com.ruoyi.biz.domain.CasePhase;
import com.ruoyi.biz.domain.CaseType;
import com.ruoyi.biz.domain.LitigateType;
import com.ruoyi.biz.service.caseinfo.ICaseInfoClosedService;
import com.ruoyi.biz.service.casepahse.ICasePhaseService;
import com.ruoyi.biz.service.casetype.ICaseTypeService;
import com.ruoyi.biz.service.casetype.ILitigateTypeService;
import com.ruoyi.biz.service.diskfile.IFileItemStoreService;
import com.ruoyi.common.core.domain.CxSelect;
import com.ruoyi.common.core.page.PageQO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.interceptor.anno.MyPermissions;
import com.ruoyi.web.controller.biz.data.CaseStatus;
import com.ruoyi.web.controller.biz.data.IdName;
import com.ruoyi.web.controller.core.impl.BaseBQCtrollerExImpls;

/**
 * 信息
 * 
 * @author riverbo
 */
@MyPermissions("案件结案信息")
@Controller
@RequestMapping("biz/caseinfo/closed")
public class CaseInfoClosedController
		extends BaseBQCtrollerExImpls<ICaseInfoClosedService, CaseInfo, CaseInfoClosedBO, CaseInfoQO, CaseInfoClosedDTO> {
	
	@Autowired
    private HttpServletRequest request;

	@Autowired
	private ICaseTypeService caseTypeService;

	@Autowired
	private ILitigateTypeService litigateTypeService;

	@Autowired
	private ICasePhaseService casePhaseService;
	
	@Autowired
	private IFileItemStoreService storeService;

	@Override
	public String query(ModelMap mmap) throws Exception {
		mmap.put("canAdd", false);
		mmap.put("canEdit", true);
		mmap.put("canCheck", false);
		//
		List<IdName> caseStatus = CaseStatus.getList();
		mmap.put("caseStatus", caseStatus);
		mmap.put("curStatus", 2);
		//
		return super.query(mmap);
	}

	@Override
	public TableDataInfo query(CaseInfoQO q, PageQO page) throws Exception {
		q.setLawyerId(super.getUserId());
		List<Integer> selectStatus = new ArrayList<>();
		selectStatus.add(3);
		selectStatus.add(2);
		q.setSelectStatus(selectStatus);
		q.setStatus(null);
		return super.query(q, page);
	}

	@Override
	public String add(ModelMap mmap) throws Exception {
		List<CxSelect> lsCaseType = getCaseTypeData();
		mmap.put("ctData", lsCaseType);
		//
		List<CasePhase> lsCasePhase = casePhaseService.selectAll();
		mmap.put("casePhases", lsCasePhase);
		//
		CaseInfoBO vo = new CaseInfoBO();
		vo.setCaseTypeId(2);
		// vo.setLitigateTypeId(1);
		mmap.put("vo", vo);
		return super.add(mmap);
	}
	
	@Override
	public String view(@PathVariable("id") Long id, ModelMap mmap) throws Exception {
		List<CxSelect> lsCaseType = getCaseTypeData();
		mmap.put("ctData", lsCaseType);
		//
		List<CasePhase> lsCasePhase = casePhaseService.selectAll();
		mmap.put("casePhases", lsCasePhase);
		//
		List<IdName> caseStatus = CaseStatus.getList();
		mmap.put("caseStatus", caseStatus);
		//
		return super.view(id, mmap);
	}

	@Override
	public String edit(@PathVariable("id") Long id, ModelMap mmap) throws Exception {
		List<CxSelect> lsCaseType = getCaseTypeData();
		mmap.put("ctData", lsCaseType);
		//
		List<CasePhase> lsCasePhase = casePhaseService.selectAll();
		mmap.put("casePhases", lsCasePhase);
		//
		return super.edit(id, mmap);
	}

	@Override
	public String check(@PathVariable("id") Long id, ModelMap mmap) throws Exception {
		List<CxSelect> lsCaseType = getCaseTypeData();
		mmap.put("ctData", lsCaseType);
		//
		List<CasePhase> lsCasePhase = casePhaseService.selectAll();
		mmap.put("casePhases", lsCasePhase);
		//
		return super.check(id, mmap);
	}

	protected List<CxSelect> getCaseTypeData() {
		List<CxSelect> cxList = new ArrayList<CxSelect>();
		{
			List<CaseType> lsCaseType = caseTypeService.selectAll();
			for (CaseType u : lsCaseType) {
				CxSelect cxSelectRoot = new CxSelect(String.valueOf(u.getCaseTypeId()), u.getCaseTypeName());
				List<CxSelect> subList = new ArrayList<CxSelect>();
				//
				List<LitigateType> lsLt = litigateTypeService.selectAll();
				for (LitigateType lt : lsLt) {
					if (u.getCaseTypeId().equals(2)) {
						if ( !lt.getLitigateTypeId().equals(4) ) {
							subList.add(new CxSelect(String.valueOf(lt.getLitigateTypeId()), lt.getLitigateTypeName()));
						}
					} else {
						subList.add(new CxSelect(String.valueOf(lt.getLitigateTypeId()), lt.getLitigateTypeName()));
					}
				}
				cxSelectRoot.setS(subList);
				//
				cxList.add(cxSelectRoot);
			}
		}
		return cxList;
	}

	//@Override
	@PostMapping("/upload")
	public String upload(@ModelAttribute CaseUploadFileDTO dto, ModelMap model, @RequestParam("file") MultipartFile file) throws Exception {
		String msgVal = null;
		try {
		  if (dto.getCaseId() != null && dto.getIdx() != null ) {
		      String sub = String.format("caseinfo/%d/%d/%d", dto.getCaseId(), dto.getCasePhaseId(), dto.getIdx());
		      storeService.save(file, sub);
		      msgVal = "上传成功: " + file.getOriginalFilename();
		  } else {
		      msgVal = "上传失败: " + file.getOriginalFilename() + ". Error: " + "file idx is null.";
		  }
		} catch (Exception e) {
		  msgVal = "上传失败: " + file.getOriginalFilename() + ". Error: " + e.getMessage();
		}
		//String msgKey = String.format("message_%d", dto.getIdx());
		String msgKey = "message";
		model.addAttribute(msgKey, msgVal);
		model.addAttribute("curIdx", dto.getIdx());
	    if (dto.getCaseId() != null) {
	    	return edit(dto.getCaseId().longValue(), model);
	    } else {
	    	return edit(0L, model);
	    }
	}
	
	//@Override
//	@PostMapping("/upload/{caseId}/{item}")
//	public String uploadId(@PathVariable Integer caseId, @PathVariable Integer item, @RequestParam("file") MultipartFile file, ModelMap model) throws Exception {
//		String msgVal = null;
//		try {
//		  if (caseId != null && item != null ) {
//		      String sub = String.format("%d/%d", caseId, item);
//		      storeService.save(file, sub);
//		      msgVal = "Uploaded the file successfully: " + file.getOriginalFilename();
//		  } else {
//		      msgVal = "Could not upload the file: " + file.getOriginalFilename() + ". Error: " + "file idx is null.";
//		  }
//		} catch (Exception e) {
//		  msgVal = "Could not upload the file: " + file.getOriginalFilename() + ". Error: " + e.getMessage();
//		}
//		//String msgKey = String.format("message_%d", dto.getIdx());
//		String msgKey = "message";
//		model.addAttribute(msgKey, msgVal);
//		model.addAttribute("curIdx", item);
//	    if (caseId != null) {
//	    	return edit(caseId.longValue(), model);
//	    } else {
//	    	return edit(0L, model);
//	    }
//	}
	
	@GetMapping("/download/{caseId}/{casePhaseId}/{item}/{filename:.+}")
	public ResponseEntity<Resource> download(@PathVariable Integer caseId, @PathVariable Integer casePhaseId, @PathVariable Integer item, @PathVariable String filename) throws Exception {
		String sub = String.format("caseinfo/%d/%d/%d", caseId, casePhaseId, item);
		Resource file = storeService.load(filename, sub);
//		HttpHeaders httpHeaders = new HttpHeaders();
//		httpHeaders.add("Content-Disposition","attachment; filename="+new String(file.getFilename().getBytes("UTF-8"),"ISO8859-1"));
        //
//		return ResponseEntity.ok()
//                .headers(httpHeaders)
//                .contentLength(file.contentLength())
//                .contentType(MediaType.parseMediaType("application/octet-stream"))
//                .body(file);		
		return ResponseEntity.ok()
	    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + new String(file.getFilename().getBytes("UTF-8"),"ISO8859-1") + "\"")
	      .contentLength(file.contentLength())
	      .contentType(MediaType.parseMediaType("application/octet-stream")).body(file);
	}

	//@Override
	@GetMapping("/delete/{caseId}/{casePhaseId}/{item}/{filename:.+}")
	public String delete(@PathVariable Integer caseId, @PathVariable Integer item, @PathVariable Integer casePhaseId, @PathVariable String filename, Model model, RedirectAttributes redirectAttributes) {
		String msgKey = "message";
	    String msgVal = null;
	    try {
		  String sub = String.format("caseinfo/%d/%d/%d", caseId, casePhaseId, item);
	      boolean existed = storeService.delete(filename, sub);
	      if (existed) {
	    	  msgVal = "删除成功: " + filename;
	      } else {
	    	  msgVal = "文件不存在!";
	      }
	    } catch (Exception e) {
	       msgVal = "删除失败: " + filename + ". Error: " + e.getMessage();
	    }
	    FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	    flashMap.put("curIdx", item);
	    flashMap.put(msgKey, msgVal);
	    return "redirect:/biz/caseinfo/closed/edit/" + caseId;
	}
	
}